package com.atguigu.distributed.lock.leecode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *力扣中等207：课程表
 */
public class CanFinish {
    List<List<Integer>> edges;
    int[] visited;
    boolean valid = true;


    public boolean canFinish(int numCourses,int[][] prerequisites){
        edges = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) {
            edges.add(new ArrayList<Integer>());
        }
        visited = new int[numCourses];
        for(int[] info:prerequisites){
            edges.get(info[1]).add(info[0]);
        }
        for (int i = 0; i < numCourses && valid; i++) {
            if(visited[i]==0){
                dfs(i);
            }
        }
        return valid;
    }
    public void dfs(int u){
        visited[u] = 1;
        for(int v:edges.get(u)){
            if(visited[v]==0){
                dfs(v);
                if(!valid){
                    return;
                }
            }else if(visited[v]==1){
                valid = false;
                return;
            }
        }
        visited[u] = 2;
    }
    public boolean canFinish2(int numCourses, int[][] prerequisites) {
        Set<Integer> dummySet = new HashSet<>();

        for (int i = 0; i < prerequisites.length; i++) {
            int[] pre = prerequisites[i];
            for (int j = 0; j < pre.length; j++) {
                if(dummySet.contains(pre[j])){
                    return false;
                }
                dummySet.add(pre[j]);
            }


        }
        return true;

    }
}
